package com.warom.sdg.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.warom.sdg.dao.PlcDataDao;
import com.warom.sdg.dao.PlcDataDao_Impl;
import com.warom.sdg.dao.PlcDeviceDao;
import com.warom.sdg.dao.PlcDeviceDao_Impl;
import com.warom.sdg.dao.UserDao;
import com.warom.sdg.dao.UserDao_Impl;
import com.warom.sdg.dao.OperationLogDao;
import com.warom.sdg.dao.OperationLogDao_Impl;
import com.warom.sdg.dao.GrainSituationDao;
import com.warom.sdg.dao.GrainSituationDao_Impl;
import com.warom.sdg.dao.VentilationConfigDao;
import com.warom.sdg.dao.VentilationConfigDao_Impl;
import com.warom.sdg.dao.ThresholdSettingDao;
import com.warom.sdg.dao.ThresholdSettingDao_Impl;
import com.warom.sdg.dao.AlarmRecordDao;
import com.warom.sdg.dao.AlarmRecordDao_Impl;
import com.warom.sdg.model.AlarmRecordEntity;
import com.warom.sdg.model.GrainSituationEntity;
import com.warom.sdg.model.OperationLogEntity;
import com.warom.sdg.model.PlcDataEntity;
import com.warom.sdg.model.PlcDeviceEntity;
import com.warom.sdg.model.UserEntity;
import com.warom.sdg.model.VentilationConfigEntity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * PLC数据库类
 * 使用SQLite原生API实现数据库操作
 */
public class SdgDatabase extends SQLiteOpenHelper {
    private static final String TAG = "SdgDatabase";
    
    // 数据库信息
    private static final String DATABASE_NAME = "sdg.db";
    private static final int DATABASE_VERSION = 1; // 开发阶段保持版本为1
    
    // 表名
    public static final String TABLE_PLC_DATA = "plc_data";
    public static final String TABLE_PLC_DEVICES = "plc_devices";
    public static final String TABLE_USERS = "users";
    public static final String TABLE_OPERATION_LOGS = "operation_logs";
    public static final String TABLE_PEST_DETECTION = "pest_detection";
    public static final String TABLE_GRAIN_SITUATION = "grainsituation";
    public static final String TABLE_VENTILATION_CONFIG = "ventilation_config";
    public static final String TABLE_THRESHOLD_SETTINGS = "threshold_settings";
    public static final String TABLE_ALARM_RECORDS = "alarm_records";
    
    // PLC数据表列名
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_DEVICE_ID = "deviceId";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_ADDRESS = "address";
    public static final String COLUMN_TYPE = "type";
    public static final String COLUMN_VALUE = "value";
    public static final String COLUMN_UNIT = "unit";
    public static final String COLUMN_TIMESTAMP = "timestamp";
    public static final String COLUMN_TIME_STRING = "timeString";
    
    // PLC设备表列名
    public static final String COLUMN_DEVICE_NAME = "deviceName";
    public static final String COLUMN_DEVICE_IP = "deviceIp";
    public static final String COLUMN_DEVICE_PORT = "devicePort";
    public static final String COLUMN_UNIT_ID = "unitId";
    public static final String COLUMN_PROTOCOL = "protocol";
    public static final String COLUMN_IS_ACTIVE = "isActive";
    public static final String COLUMN_DESCRIPTION = "description";
    public static final String COLUMN_LAST_CONNECT_TIME = "lastConnectTime";
    public static final String COLUMN_DEVICE_TYPE_ID = "deviceTypeId";
    
    // 用户表列名
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_USER_NAME = "name";
    public static final String COLUMN_ROLE = "role";
    public static final String COLUMN_LAST_LOGIN_TIME = "lastLoginTime";
    
    // 操作日志表列名
    public static final String COLUMN_OPERATION_USERNAME = "operation_username";
    public static final String COLUMN_OPERATION_TYPE = "operation_type";
    public static final String COLUMN_OPERATION_DESCRIPTION = "operation_description";
    public static final String COLUMN_OPERATION_PAGE = "operation_page";
    public static final String COLUMN_OPERATION_TARGET = "operation_target";
    public static final String COLUMN_OPERATION_STATUS = "operation_status";
    public static final String COLUMN_OPERATION_ERROR_MESSAGE = "operation_error_message";
    public static final String COLUMN_OPERATION_TIME = "operation_time";
    public static final String COLUMN_OPERATION_TIME_STRING = "operation_time_string";
    public static final String COLUMN_OPERATION_IP_ADDRESS = "operation_ip_address";
    public static final String COLUMN_OPERATION_USER_AGENT = "operation_user_agent";
    
    // 虫情检测表列名
    public static final String COLUMN_PEST_TYPE = "pest_type";
    public static final String COLUMN_CONFIDENCE = "confidence";
    public static final String COLUMN_COUNT = "count";
    public static final String COLUMN_IMAGE_URL = "image_url";
    public static final String COLUMN_STATUS = "status";
    
    // 粮情数据表列名
    public static final String COLUMN_CABLE_NO = "cable_no";
    public static final String COLUMN_CABLE_NAME = "cable_name";
    public static final String COLUMN_POINT_NO = "point_no";
    public static final String COLUMN_TEMPERATURE = "temperature";
    public static final String COLUMN_HUMIDITY = "humidity";
    public static final String COLUMN_REMARK = "remark";
    
    // 通风配置表列名
    public static final String COLUMN_VC_DEVICE_TYPE = "device_type";
    public static final String COLUMN_VC_TARGET_TEMPERATURE = "target_temperature";
    public static final String COLUMN_VC_TARGET_HUMIDITY = "target_humidity";
    public static final String COLUMN_VC_START_TIME = "start_time";
    public static final String COLUMN_VC_END_TIME = "end_time";
    public static final String COLUMN_VC_DURATION = "duration";
    
    // 阈值设置表列名
    public static final String COLUMN_PARAM_TYPE = "param_type";
    public static final String COLUMN_MIN_VALUE = "min_value";
    public static final String COLUMN_MAX_VALUE = "max_value";
    public static final String COLUMN_CREATE_TIME = "create_time";
    public static final String COLUMN_UPDATE_TIME = "update_time";

    // 报警记录表列名
    public static final String COLUMN_ALARM_TYPE = "alarm_type";
    public static final String COLUMN_LOCATION = "location";
    public static final String COLUMN_THRESHOLD_MIN = "threshold_min";
    public static final String COLUMN_THRESHOLD_MAX = "threshold_max";
    public static final String COLUMN_LEVEL = "level";
    public static final String COLUMN_HANDLE_TIME = "handle_time";
    public static final String COLUMN_HANDLE_USER = "handle_user";
    public static final String COLUMN_HANDLE_DESCRIPTION = "handle_description";
    public static final String COLUMN_CREATE_TIME_STRING = "create_time_string";
    
    // PLC数据表创建SQL语句
    private static final String CREATE_TABLE_PLC_DATA = 
            "CREATE TABLE " + TABLE_PLC_DATA + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_DEVICE_ID + " INTEGER, " +
            COLUMN_NAME + " TEXT, " +
            COLUMN_ADDRESS + " TEXT, " +
            COLUMN_TYPE + " TEXT, " +
            COLUMN_VALUE + " TEXT, " +
            COLUMN_UNIT + " TEXT, " +
            COLUMN_TIMESTAMP + " INTEGER, " +
            COLUMN_TIME_STRING + " TEXT, " +
            "FOREIGN KEY (" + COLUMN_DEVICE_ID + ") REFERENCES " + 
                TABLE_PLC_DEVICES + "(" + COLUMN_ID + ") ON DELETE CASCADE" +
            ")";
    
    // 设备表创建SQL语句
    private static final String CREATE_TABLE_PLC_DEVICES = 
            "CREATE TABLE " + TABLE_PLC_DEVICES + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_DEVICE_NAME + " TEXT, " +
            COLUMN_DEVICE_IP + " TEXT, " +
            COLUMN_DEVICE_PORT + " INTEGER, " +
            COLUMN_UNIT_ID + " INTEGER, " +
            COLUMN_PROTOCOL + " TEXT, " +
            COLUMN_IS_ACTIVE + " INTEGER, " +
            COLUMN_DESCRIPTION + " TEXT, " +
            COLUMN_LAST_CONNECT_TIME + " INTEGER, " +
            COLUMN_DEVICE_TYPE_ID + " INTEGER DEFAULT 1" +
            ")";
    
    // 用户表创建SQL语句
    private static final String CREATE_TABLE_USERS = 
            "CREATE TABLE " + TABLE_USERS + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_USERNAME + " TEXT UNIQUE NOT NULL, " +
            COLUMN_PASSWORD + " TEXT NOT NULL, " +
            COLUMN_USER_NAME + " TEXT, " +
            COLUMN_ROLE + " TEXT NOT NULL, " +
            COLUMN_LAST_LOGIN_TIME + " INTEGER" +
            ")";
    
    // 操作日志表创建SQL语句
    private static final String CREATE_TABLE_OPERATION_LOGS = 
            "CREATE TABLE " + TABLE_OPERATION_LOGS + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_OPERATION_USERNAME + " TEXT, " +
            COLUMN_OPERATION_TYPE + " TEXT, " +
            COLUMN_OPERATION_DESCRIPTION + " TEXT, " +
            COLUMN_OPERATION_PAGE + " TEXT, " +
            COLUMN_OPERATION_TARGET + " TEXT, " +
            COLUMN_OPERATION_STATUS + " TEXT, " +
            COLUMN_OPERATION_ERROR_MESSAGE + " TEXT, " +
            COLUMN_OPERATION_TIME + " INTEGER, " +
            COLUMN_OPERATION_TIME_STRING + " TEXT, " +
            COLUMN_OPERATION_IP_ADDRESS + " TEXT, " +
            COLUMN_OPERATION_USER_AGENT + " TEXT" +
            ")";
    
    // 创建索引的SQL语句
    private static final String CREATE_INDEX_PLC_DATA_DEVICE_ID =
            "CREATE INDEX index_plc_data_deviceId ON " + 
            TABLE_PLC_DATA + "(" + COLUMN_DEVICE_ID + ")";
    
    private static final String CREATE_INDEX_USERS_USERNAME =
            "CREATE INDEX index_users_username ON " + 
            TABLE_USERS + "(" + COLUMN_USERNAME + ")";
    
    private static final String CREATE_INDEX_OPERATION_LOGS_USERNAME =
            "CREATE INDEX index_operation_logs_username ON " + 
            TABLE_OPERATION_LOGS + "(" + COLUMN_OPERATION_USERNAME + ")";
            
    private static final String CREATE_INDEX_OPERATION_LOGS_TIME =
            "CREATE INDEX index_operation_logs_time ON " + 
            TABLE_OPERATION_LOGS + "(" + COLUMN_OPERATION_TIME + ")";
            
    // 虫情检测表创建SQL语句
    private static final String CREATE_TABLE_PEST_DETECTION = 
            "CREATE TABLE " + TABLE_PEST_DETECTION + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_DEVICE_ID + " INTEGER, " +
            COLUMN_PEST_TYPE + " TEXT, " +
            COLUMN_CONFIDENCE + " REAL, " +
            COLUMN_COUNT + " INTEGER, " +
            COLUMN_IMAGE_URL + " TEXT, " +
            COLUMN_TIMESTAMP + " INTEGER, " +
            COLUMN_STATUS + " TEXT)";
    
    // 虫情检测表索引
    private static final String CREATE_INDEX_PEST_DETECTION_DEVICE_ID =
            "CREATE INDEX index_pest_detection_device_id ON " + 
            TABLE_PEST_DETECTION + "(" + COLUMN_DEVICE_ID + ")";
            
    private static final String CREATE_INDEX_PEST_DETECTION_TIMESTAMP =
            "CREATE INDEX index_pest_detection_timestamp ON " + 
            TABLE_PEST_DETECTION + "(" + COLUMN_TIMESTAMP + ")";
    
    // 粮情数据表创建SQL语句
    private static final String CREATE_TABLE_GRAIN_SITUATION = 
            "CREATE TABLE " + TABLE_GRAIN_SITUATION + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_CABLE_NO + " INTEGER, " +
            COLUMN_POINT_NO + " INTEGER, " +
            COLUMN_TEMPERATURE + " REAL, " +
            COLUMN_HUMIDITY + " REAL, " +
            COLUMN_TIMESTAMP + " INTEGER, " +
            COLUMN_TIME_STRING + " TEXT, " +
            COLUMN_DEVICE_ID + " INTEGER, " +
            COLUMN_STATUS + " INTEGER, " +
            COLUMN_REMARK + " TEXT" +
            ")";
    
    // 粮情数据表索引
    private static final String CREATE_INDEX_GRAIN_SITUATION_CABLE_NO =
            "CREATE INDEX index_grain_situation_cable_no ON " + 
            TABLE_GRAIN_SITUATION + "(" + COLUMN_CABLE_NO + ")";
            
    private static final String CREATE_INDEX_GRAIN_SITUATION_TIMESTAMP =
            "CREATE INDEX index_grain_situation_timestamp ON " + 
            TABLE_GRAIN_SITUATION + "(" + COLUMN_TIMESTAMP + ")";
    
    // 通风配置表创建SQL语句
    private static final String CREATE_TABLE_VENTILATION_CONFIG =
            "CREATE TABLE " + TABLE_VENTILATION_CONFIG + " (" +
                    COLUMN_VC_DEVICE_TYPE + " TEXT PRIMARY KEY NOT NULL, " +
                    COLUMN_VC_TARGET_TEMPERATURE + " INTEGER NOT NULL, " +
                    COLUMN_VC_TARGET_HUMIDITY + " INTEGER NOT NULL, " +
                    COLUMN_VC_START_TIME + " TEXT, " +
                    COLUMN_VC_END_TIME + " TEXT, " +
                    COLUMN_VC_DURATION + " INTEGER NOT NULL)";

    // 通风配置表索引
    private static final String CREATE_INDEX_VENTILATION_CONFIG_DEVICE_TYPE =
            "CREATE INDEX index_ventilation_config_device_type ON " + 
            TABLE_VENTILATION_CONFIG + "(" + COLUMN_VC_DEVICE_TYPE + ")";
            
    private static final String CREATE_INDEX_VENTILATION_CONFIG_TEMPERATURE =
            "CREATE INDEX index_ventilation_config_temperature ON " + 
            TABLE_VENTILATION_CONFIG + "(" + COLUMN_VC_TARGET_TEMPERATURE + ")";

    // 阈值设置表创建SQL语句
    private static final String CREATE_TABLE_THRESHOLD_SETTINGS =
            "CREATE TABLE " + TABLE_THRESHOLD_SETTINGS + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_PARAM_TYPE + " TEXT NOT NULL UNIQUE, " +
                    COLUMN_MIN_VALUE + " REAL NOT NULL, " +
                    COLUMN_MAX_VALUE + " REAL NOT NULL, " +
                    COLUMN_UNIT + " TEXT NOT NULL, " +
                    COLUMN_DESCRIPTION + " TEXT, " +
                    COLUMN_CREATE_TIME + " INTEGER, " +
                    COLUMN_UPDATE_TIME + " INTEGER)";

    // 阈值设置表索引
    private static final String CREATE_INDEX_THRESHOLD_SETTINGS_PARAM_TYPE =
            "CREATE INDEX index_threshold_settings_param_type ON " + 
            TABLE_THRESHOLD_SETTINGS + "(" + COLUMN_PARAM_TYPE + ")";

    // 报警记录表创建SQL语句
    private static final String CREATE_TABLE_ALARM_RECORDS = 
            "CREATE TABLE " + TABLE_ALARM_RECORDS + " (" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_ALARM_TYPE + " TEXT NOT NULL, " +
            COLUMN_PARAM_TYPE + " TEXT NOT NULL, " +
            COLUMN_DEVICE_ID + " INTEGER, " +
            COLUMN_LOCATION + " TEXT, " +
            COLUMN_VALUE + " REAL, " +
            COLUMN_UNIT + " TEXT, " +
            COLUMN_THRESHOLD_MIN + " REAL, " +
            COLUMN_THRESHOLD_MAX + " REAL, " +
            COLUMN_LEVEL + " TEXT, " +
            COLUMN_STATUS + " TEXT, " +
            COLUMN_DESCRIPTION + " TEXT, " +
            COLUMN_CREATE_TIME + " INTEGER, " +
            COLUMN_CREATE_TIME_STRING + " TEXT, " +
            COLUMN_HANDLE_TIME + " INTEGER, " +
            COLUMN_HANDLE_USER + " TEXT, " +
            COLUMN_HANDLE_DESCRIPTION + " TEXT, " +
            "FOREIGN KEY (" + COLUMN_DEVICE_ID + ") REFERENCES " + 
                TABLE_PLC_DEVICES + "(" + COLUMN_ID + ") ON DELETE SET NULL" +
            ")";

    // 报警记录表索引
    private static final String CREATE_INDEX_ALARM_RECORDS_TYPE =
            "CREATE INDEX index_alarm_records_type ON " + 
            TABLE_ALARM_RECORDS + "(" + COLUMN_ALARM_TYPE + ")";

    private static final String CREATE_INDEX_ALARM_RECORDS_PARAM_TYPE =
            "CREATE INDEX index_alarm_records_param_type ON " + 
            TABLE_ALARM_RECORDS + "(" + COLUMN_PARAM_TYPE + ")";

    private static final String CREATE_INDEX_ALARM_RECORDS_DEVICE_ID =
            "CREATE INDEX index_alarm_records_device_id ON " + 
            TABLE_ALARM_RECORDS + "(" + COLUMN_DEVICE_ID + ")";

    private static final String CREATE_INDEX_ALARM_RECORDS_STATUS =
            "CREATE INDEX index_alarm_records_status ON " + 
            TABLE_ALARM_RECORDS + "(" + COLUMN_STATUS + ")";

    private static final String CREATE_INDEX_ALARM_RECORDS_LEVEL =
            "CREATE INDEX index_alarm_records_level ON " + 
            TABLE_ALARM_RECORDS + "(" + COLUMN_LEVEL + ")";

    private static final String CREATE_INDEX_ALARM_RECORDS_CREATE_TIME =
            "CREATE INDEX index_alarm_records_create_time ON " + 
            TABLE_ALARM_RECORDS + "(" + COLUMN_CREATE_TIME + ")";

    // 单例实例
    private static volatile SdgDatabase INSTANCE;
    
    // DAO实例
    private PlcDataDao plcDataDao;
    private PlcDeviceDao plcDeviceDao;
    private UserDao userDao;
    private OperationLogDao operationLogDao;
    private GrainSituationDao grainSituationDao;
    private VentilationConfigDao ventilationConfigDao;
    private ThresholdSettingDao thresholdSettingDao;
    private AlarmRecordDao alarmRecordDao;
    
    /**
     * 获取数据库实例
     * @param context 上下文
     * @return 数据库实例
     */
    public static synchronized SdgDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new SdgDatabase(context.getApplicationContext());
        }
        return INSTANCE;
    }
    
    /**
     * 构造函数
     * @param context 上下文
     */
    private SdgDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        
        // 创建DAO实现类
        this.plcDataDao = new PlcDataDao_Impl(this);
        this.plcDeviceDao = new PlcDeviceDao_Impl(this);
        this.userDao = new UserDao_Impl(this);
        this.operationLogDao = new OperationLogDao_Impl(this);
        this.grainSituationDao = new GrainSituationDao_Impl(this);
        this.ventilationConfigDao = new VentilationConfigDao_Impl(this);
        this.thresholdSettingDao = new ThresholdSettingDao_Impl(this);
        this.alarmRecordDao = new AlarmRecordDao_Impl(this);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            // 创建表
            db.execSQL(CREATE_TABLE_PLC_DATA);
            db.execSQL(CREATE_TABLE_PLC_DEVICES);
            db.execSQL(CREATE_TABLE_USERS);
            db.execSQL(CREATE_TABLE_OPERATION_LOGS);
            db.execSQL(CREATE_TABLE_PEST_DETECTION);
            db.execSQL(CREATE_TABLE_GRAIN_SITUATION);
            db.execSQL(CREATE_TABLE_VENTILATION_CONFIG);
            db.execSQL(CREATE_TABLE_THRESHOLD_SETTINGS);
            db.execSQL(CREATE_TABLE_ALARM_RECORDS);
            
            // 创建索引
            db.execSQL(CREATE_INDEX_PLC_DATA_DEVICE_ID);
            db.execSQL(CREATE_INDEX_USERS_USERNAME);
            db.execSQL(CREATE_INDEX_OPERATION_LOGS_USERNAME);
            db.execSQL(CREATE_INDEX_OPERATION_LOGS_TIME);
            db.execSQL(CREATE_INDEX_PEST_DETECTION_DEVICE_ID);
            db.execSQL(CREATE_INDEX_PEST_DETECTION_TIMESTAMP);
            db.execSQL(CREATE_INDEX_GRAIN_SITUATION_CABLE_NO);
            db.execSQL(CREATE_INDEX_GRAIN_SITUATION_TIMESTAMP);
            db.execSQL(CREATE_INDEX_VENTILATION_CONFIG_DEVICE_TYPE);
            db.execSQL(CREATE_INDEX_VENTILATION_CONFIG_TEMPERATURE);
            db.execSQL(CREATE_INDEX_THRESHOLD_SETTINGS_PARAM_TYPE);
            db.execSQL(CREATE_INDEX_ALARM_RECORDS_TYPE);
            db.execSQL(CREATE_INDEX_ALARM_RECORDS_PARAM_TYPE);
            db.execSQL(CREATE_INDEX_ALARM_RECORDS_DEVICE_ID);
            db.execSQL(CREATE_INDEX_ALARM_RECORDS_STATUS);
            db.execSQL(CREATE_INDEX_ALARM_RECORDS_LEVEL);
            db.execSQL(CREATE_INDEX_ALARM_RECORDS_CREATE_TIME);
            
            // 创建默认管理员用户
            createDefaultAdminUser(db);
            
            // 创建默认设备
            createDefaultDevices(db);
            
            // 创建默认通风配置
            createDefaultVentilationConfig(db);
            
            // 创建默认阈值设置
            createDefaultThresholdSettings(db);

            // 创建默认报警记录
            createDefaultAlarmRecords(db);
            
            Log.i(TAG, "数据库初始化成功");
        } catch (Exception e) {
            Log.e(TAG, "数据库初始化失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建默认阈值设置
     * @param db 数据库实例
     */
    private void createDefaultThresholdSettings(SQLiteDatabase db) {
        Log.i(TAG, "创建默认阈值设置");
        
        long currentTime = System.currentTimeMillis();
        
        // 温度阈值
        ContentValues tempValues = new ContentValues();
        tempValues.put(COLUMN_PARAM_TYPE, "temperature");
        tempValues.put(COLUMN_MIN_VALUE, 5);
        tempValues.put(COLUMN_MAX_VALUE, 35);
        tempValues.put(COLUMN_UNIT, "℃");
        tempValues.put(COLUMN_DESCRIPTION, "粮食储存适宜温度范围");
        tempValues.put(COLUMN_CREATE_TIME, currentTime);
        tempValues.put(COLUMN_UPDATE_TIME, currentTime);
        db.insert(TABLE_THRESHOLD_SETTINGS, null, tempValues);
        
        // 湿度阈值
        ContentValues humidityValues = new ContentValues();
        humidityValues.put(COLUMN_PARAM_TYPE, "humidity");
        humidityValues.put(COLUMN_MIN_VALUE, 45);
        humidityValues.put(COLUMN_MAX_VALUE, 75);
        humidityValues.put(COLUMN_UNIT, "%");
        humidityValues.put(COLUMN_DESCRIPTION, "粮食储存适宜湿度范围");
        humidityValues.put(COLUMN_CREATE_TIME, currentTime);
        humidityValues.put(COLUMN_UPDATE_TIME, currentTime);
        db.insert(TABLE_THRESHOLD_SETTINGS, null, humidityValues);
        
        // 虫情阈值
        ContentValues pestValues = new ContentValues();
        pestValues.put(COLUMN_PARAM_TYPE, "pest");
        pestValues.put(COLUMN_MIN_VALUE, 0);
        pestValues.put(COLUMN_MAX_VALUE, 20);
        pestValues.put(COLUMN_UNIT, "只/kg");
        pestValues.put(COLUMN_DESCRIPTION, "粮食虫害警戒阈值");
        pestValues.put(COLUMN_CREATE_TIME, currentTime);
        pestValues.put(COLUMN_UPDATE_TIME, currentTime);
        db.insert(TABLE_THRESHOLD_SETTINGS, null, pestValues);
        
        // 氧气浓度阈值
        ContentValues oxygenValues = new ContentValues();
        oxygenValues.put(COLUMN_PARAM_TYPE, "oxygen");
        oxygenValues.put(COLUMN_MIN_VALUE, 19);
        oxygenValues.put(COLUMN_MAX_VALUE, 23);
        oxygenValues.put(COLUMN_UNIT, "%");
        oxygenValues.put(COLUMN_DESCRIPTION, "安全氧气浓度范围");
        oxygenValues.put(COLUMN_CREATE_TIME, currentTime);
        oxygenValues.put(COLUMN_UPDATE_TIME, currentTime);
        db.insert(TABLE_THRESHOLD_SETTINGS, null, oxygenValues);
        
        // 二氧化碳浓度阈值
        ContentValues co2Values = new ContentValues();
        co2Values.put(COLUMN_PARAM_TYPE, "co2");
        co2Values.put(COLUMN_MIN_VALUE, 0);
        co2Values.put(COLUMN_MAX_VALUE, 0.5);
        co2Values.put(COLUMN_UNIT, "%");
        co2Values.put(COLUMN_DESCRIPTION, "安全二氧化碳浓度范围");
        co2Values.put(COLUMN_CREATE_TIME, currentTime);
        co2Values.put(COLUMN_UPDATE_TIME, currentTime);
        db.insert(TABLE_THRESHOLD_SETTINGS, null, co2Values);
        
        // 磷化氢浓度阈值
        ContentValues ph3Values = new ContentValues();
        ph3Values.put(COLUMN_PARAM_TYPE, "ph3");
        ph3Values.put(COLUMN_MIN_VALUE, 0);
        ph3Values.put(COLUMN_MAX_VALUE, 0.01);
        ph3Values.put(COLUMN_UNIT, "mg/m³");
        ph3Values.put(COLUMN_DESCRIPTION, "安全磷化氢浓度范围");
        ph3Values.put(COLUMN_CREATE_TIME, currentTime);
        ph3Values.put(COLUMN_UPDATE_TIME, currentTime);
        db.insert(TABLE_THRESHOLD_SETTINGS, null, ph3Values);
        
        Log.i(TAG, "默认阈值设置创建完成");
    }
    
    /**
     * 创建默认设备数据
     * @param db 数据库
     */
    private void createDefaultDevices(SQLiteDatabase db) {
        try {
            // 创建PLC设备1
            ContentValues device1 = new ContentValues();
            device1.put(COLUMN_DEVICE_NAME, "PLC设备1");
            device1.put(COLUMN_DEVICE_IP, "192.168.0.1");
            device1.put(COLUMN_DEVICE_PORT, 502);
            device1.put(COLUMN_UNIT_ID, 1);
            device1.put(COLUMN_PROTOCOL, "Siemens S7-1200");
            device1.put(COLUMN_IS_ACTIVE, 1); // online
            device1.put(COLUMN_DESCRIPTION, "1号机房主控PLC");
            device1.put(COLUMN_DEVICE_TYPE_ID, 1);
            db.insert(TABLE_PLC_DEVICES, null, device1);
            
            // 创建PLC设备2
            ContentValues device2 = new ContentValues();
            device2.put(COLUMN_DEVICE_NAME, "PLC设备2");
            device2.put(COLUMN_DEVICE_IP, "192.168.0.51");
            device2.put(COLUMN_DEVICE_PORT, 502);
            device2.put(COLUMN_UNIT_ID, 1);
            device2.put(COLUMN_PROTOCOL, "Mitsubishi FX3U");
            device2.put(COLUMN_IS_ACTIVE, 0); // offline
            device2.put(COLUMN_DESCRIPTION, "温湿度控制PLC");
            device2.put(COLUMN_DEVICE_TYPE_ID, 2);
            db.insert(TABLE_PLC_DEVICES, null, device2);
            
            // 创建PLC设备3
            ContentValues device3 = new ContentValues();
            device3.put(COLUMN_DEVICE_NAME, "PLC设备3");
            device3.put(COLUMN_DEVICE_IP, "192.168.0.7");
            device3.put(COLUMN_DEVICE_PORT, 23);
            device3.put(COLUMN_UNIT_ID, 1);
            device3.put(COLUMN_PROTOCOL, "Omron CP1E");
            device3.put(COLUMN_IS_ACTIVE, 1); // online
            device3.put(COLUMN_DESCRIPTION, "粮库仓储监控系统");
            device3.put(COLUMN_DEVICE_TYPE_ID, 3);
            db.insert(TABLE_PLC_DEVICES, null, device3);
            
            Log.i(TAG, "创建默认设备数据成功");
        } catch (Exception e) {
            Log.e(TAG, "创建默认设备数据失败: " + e.getMessage());
        }
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 开发阶段简化处理：直接删除所有表并重新创建
//        try {
//            // 删除所有表
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLC_DATA);
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLC_DEVICES);
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_OPERATION_LOGS);
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_PEST_DETECTION);
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRAIN_SITUATION);
//            db.execSQL("DROP TABLE IF EXISTS " + TABLE_VENTILATION_CONFIG);
//
//            // 重新创建所有表
//            onCreate(db);
//
//            Log.i(TAG, "数据库升级成功: 删除并重建所有表");
//        } catch (Exception e) {
//            Log.e(TAG, "数据库升级失败: " + e.getMessage());
//        }
    }
    
    /**
     * 创建默认管理员用户
     * @param db 数据库
     */
    private void createDefaultAdminUser(SQLiteDatabase db) {
        try {
            // 创建管理员用户
            ContentValues adminValues = new ContentValues();
            adminValues.put(COLUMN_USERNAME, "admin");
            adminValues.put(COLUMN_PASSWORD, "admin");
            adminValues.put(COLUMN_USER_NAME, "管理员");
            adminValues.put(COLUMN_ROLE, "ADMIN");
            db.insert(TABLE_USERS, null, adminValues);
            
            // 创建操作员用户
            ContentValues operatorValues = new ContentValues();
            operatorValues.put(COLUMN_USERNAME, "operator");
            operatorValues.put(COLUMN_PASSWORD, "operator");
            operatorValues.put(COLUMN_USER_NAME, "操作员");
            operatorValues.put(COLUMN_ROLE, "OPERATOR");
            db.insert(TABLE_USERS, null, operatorValues);
            
            // 创建查看员用户
            ContentValues viewerValues = new ContentValues();
            viewerValues.put(COLUMN_USERNAME, "viewer");
            viewerValues.put(COLUMN_PASSWORD, "viewer");
            viewerValues.put(COLUMN_USER_NAME, "查看员");
            viewerValues.put(COLUMN_ROLE, "VIEWER");
            db.insert(TABLE_USERS, null, viewerValues);
            
            Log.i(TAG, "创建默认用户成功：管理员、操作员、查看员");
        } catch (Exception e) {
            Log.e(TAG, "创建默认用户失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建默认通风配置数据
     * @param db 数据库
     */
    private void createDefaultVentilationConfig(SQLiteDatabase db) {
        try {
            // 创建自然通风窗配置
            ContentValues naturalWindow = new ContentValues();
            naturalWindow.put(COLUMN_VC_DEVICE_TYPE, "NATURAL_WINDOW");
            naturalWindow.put(COLUMN_VC_TARGET_TEMPERATURE, 25);
            naturalWindow.put(COLUMN_VC_TARGET_HUMIDITY, 60);
            naturalWindow.put(COLUMN_VC_START_TIME, "08:00");
            naturalWindow.put(COLUMN_VC_END_TIME, "18:00");
            naturalWindow.put(COLUMN_VC_DURATION, 30);
            db.insert(TABLE_VENTILATION_CONFIG, null, naturalWindow);
            
            // 创建轴流风机配置
            ContentValues axialFan = new ContentValues();
            axialFan.put(COLUMN_VC_DEVICE_TYPE, "AXIAL_FAN");
            axialFan.put(COLUMN_VC_TARGET_TEMPERATURE, 25);
            axialFan.put(COLUMN_VC_TARGET_HUMIDITY, 60);
            axialFan.put(COLUMN_VC_START_TIME, "08:00");
            axialFan.put(COLUMN_VC_END_TIME, "18:00");
            axialFan.put(COLUMN_VC_DURATION, 30);
            db.insert(TABLE_VENTILATION_CONFIG, null, axialFan);
            
            // 创建环流风机配置
            ContentValues circulationFan = new ContentValues();
            circulationFan.put(COLUMN_VC_DEVICE_TYPE, "CIRCULATION_FAN");
            circulationFan.put(COLUMN_VC_TARGET_TEMPERATURE, 25);
            circulationFan.put(COLUMN_VC_TARGET_HUMIDITY, 60);
            circulationFan.put(COLUMN_VC_START_TIME, "08:00");
            circulationFan.put(COLUMN_VC_END_TIME, "18:00");
            circulationFan.put(COLUMN_VC_DURATION, 30);
            db.insert(TABLE_VENTILATION_CONFIG, null, circulationFan);
            
            Log.i(TAG, "创建默认通风配置数据成功");
        } catch (Exception e) {
            Log.e(TAG, "创建默认通风配置数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取PLC数据DAO
     * @return PLC数据DAO
     */
    public PlcDataDao getPlcDataDao() {
        return plcDataDao;
    }
    
    /**
     * 获取PLC设备DAO
     * @return PLC设备DAO
     */
    public PlcDeviceDao getPlcDeviceDao() {
        return plcDeviceDao;
    }
    
    /**
     * 获取用户DAO
     * @return 用户DAO
     */
    public UserDao getUserDao() {
        return userDao;
    }
    
    /**
     * 获取操作日志DAO
     * @return 操作日志DAO
     */
    public OperationLogDao getOperationLogDao() {
        return operationLogDao;
    }
    
    /**
     * 获取粮情数据DAO
     * @return 粮情数据DAO
     */
    public GrainSituationDao getGrainSituationDao() {
        return grainSituationDao;
    }

    /**
     * 获取通风配置DAO
     * @return 通风配置DAO
     */
    public VentilationConfigDao getVentilationConfigDao() {
        return ventilationConfigDao;
    }

    /**
     * 获取阈值设置DAO
     * @return 阈值设置DAO
     */
    public ThresholdSettingDao getThresholdSettingDao() {
        return thresholdSettingDao;
    }

    /**
     * 获取报警记录DAO
     * @return 报警记录DAO
     */
    public AlarmRecordDao getAlarmRecordDao() {
        return alarmRecordDao;
    }
    
    /**
     * 关闭数据库连接
     */
    public void closeDatabase() {
        if (INSTANCE != null) {
            INSTANCE.close();
            INSTANCE = null;
        }
    }

    /**
     * 创建默认报警记录
     * @param db 数据库实例
     */
    private void createDefaultAlarmRecords(SQLiteDatabase db) {
        Log.i(TAG, "创建默认报警记录");
        
        long currentTime = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        
        // 创建粮情报警记录
        
        // 高级别温度报警
        ContentValues highTempAlarm = new ContentValues();
        highTempAlarm.put(COLUMN_ALARM_TYPE, "GRAIN");
        highTempAlarm.put(COLUMN_PARAM_TYPE, "temperature");
        highTempAlarm.put(COLUMN_DEVICE_ID, 1);
        highTempAlarm.put(COLUMN_LOCATION, "仓库1-测点3");
        highTempAlarm.put(COLUMN_VALUE, 38.5);
        highTempAlarm.put(COLUMN_UNIT, "℃");
        highTempAlarm.put(COLUMN_THRESHOLD_MIN, 5);
        highTempAlarm.put(COLUMN_THRESHOLD_MAX, 35);
        highTempAlarm.put(COLUMN_LEVEL, "HIGH");
        highTempAlarm.put(COLUMN_STATUS, "ACTIVE");
        highTempAlarm.put(COLUMN_DESCRIPTION, "温度超出安全范围");
        highTempAlarm.put(COLUMN_CREATE_TIME, currentTime - 3 * 60 * 60 * 1000); // 3小时前
        highTempAlarm.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 3 * 60 * 60 * 1000)));
        db.insert(TABLE_ALARM_RECORDS, null, highTempAlarm);
        
        // 中级别湿度报警
        ContentValues mediumHumidityAlarm = new ContentValues();
        mediumHumidityAlarm.put(COLUMN_ALARM_TYPE, "GRAIN");
        mediumHumidityAlarm.put(COLUMN_PARAM_TYPE, "humidity");
        mediumHumidityAlarm.put(COLUMN_DEVICE_ID, 1);
        mediumHumidityAlarm.put(COLUMN_LOCATION, "仓库1-测点5");
        mediumHumidityAlarm.put(COLUMN_VALUE, 78.2);
        mediumHumidityAlarm.put(COLUMN_UNIT, "%");
        mediumHumidityAlarm.put(COLUMN_THRESHOLD_MIN, 45);
        mediumHumidityAlarm.put(COLUMN_THRESHOLD_MAX, 75);
        mediumHumidityAlarm.put(COLUMN_LEVEL, "MEDIUM");
        mediumHumidityAlarm.put(COLUMN_STATUS, "ACTIVE");
        mediumHumidityAlarm.put(COLUMN_DESCRIPTION, "湿度超出安全范围");
        mediumHumidityAlarm.put(COLUMN_CREATE_TIME, currentTime - 5 * 60 * 60 * 1000); // 5小时前
        mediumHumidityAlarm.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 5 * 60 * 60 * 1000)));
        db.insert(TABLE_ALARM_RECORDS, null, mediumHumidityAlarm);
        
        // 低级别温度报警-已处理
        ContentValues lowTempAlarmHandled = new ContentValues();
        lowTempAlarmHandled.put(COLUMN_ALARM_TYPE, "GRAIN");
        lowTempAlarmHandled.put(COLUMN_PARAM_TYPE, "temperature");
        lowTempAlarmHandled.put(COLUMN_DEVICE_ID, 2);
        lowTempAlarmHandled.put(COLUMN_LOCATION, "仓库2-测点2");
        lowTempAlarmHandled.put(COLUMN_VALUE, 4.8);
        lowTempAlarmHandled.put(COLUMN_UNIT, "℃");
        lowTempAlarmHandled.put(COLUMN_THRESHOLD_MIN, 5);
        lowTempAlarmHandled.put(COLUMN_THRESHOLD_MAX, 35);
        lowTempAlarmHandled.put(COLUMN_LEVEL, "LOW");
        lowTempAlarmHandled.put(COLUMN_STATUS, "HANDLED");
        lowTempAlarmHandled.put(COLUMN_DESCRIPTION, "温度低于安全范围");
        lowTempAlarmHandled.put(COLUMN_CREATE_TIME, currentTime - 12 * 60 * 60 * 1000); // 12小时前
        lowTempAlarmHandled.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 12 * 60 * 60 * 1000)));
        lowTempAlarmHandled.put(COLUMN_HANDLE_TIME, currentTime - 10 * 60 * 60 * 1000); // 10小时前处理
        lowTempAlarmHandled.put(COLUMN_HANDLE_USER, "admin");
        lowTempAlarmHandled.put(COLUMN_HANDLE_DESCRIPTION, "已调整温控系统");
        db.insert(TABLE_ALARM_RECORDS, null, lowTempAlarmHandled);
        
        // 中级别湿度报警-已忽略
        ContentValues mediumHumidityAlarmIgnored = new ContentValues();
        mediumHumidityAlarmIgnored.put(COLUMN_ALARM_TYPE, "GRAIN");
        mediumHumidityAlarmIgnored.put(COLUMN_PARAM_TYPE, "humidity");
        mediumHumidityAlarmIgnored.put(COLUMN_DEVICE_ID, 3);
        mediumHumidityAlarmIgnored.put(COLUMN_LOCATION, "仓库3-测点1");
        mediumHumidityAlarmIgnored.put(COLUMN_VALUE, 76.5);
        mediumHumidityAlarmIgnored.put(COLUMN_UNIT, "%");
        mediumHumidityAlarmIgnored.put(COLUMN_THRESHOLD_MIN, 45);
        mediumHumidityAlarmIgnored.put(COLUMN_THRESHOLD_MAX, 75);
        mediumHumidityAlarmIgnored.put(COLUMN_LEVEL, "MEDIUM");
        mediumHumidityAlarmIgnored.put(COLUMN_STATUS, "IGNORED");
        mediumHumidityAlarmIgnored.put(COLUMN_DESCRIPTION, "湿度略高于安全范围");
        mediumHumidityAlarmIgnored.put(COLUMN_CREATE_TIME, currentTime - 24 * 60 * 60 * 1000); // 1天前
        mediumHumidityAlarmIgnored.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 24 * 60 * 60 * 1000)));
        mediumHumidityAlarmIgnored.put(COLUMN_HANDLE_TIME, currentTime - 22 * 60 * 60 * 1000); // 22小时前处理
        mediumHumidityAlarmIgnored.put(COLUMN_HANDLE_USER, "operator");
        mediumHumidityAlarmIgnored.put(COLUMN_HANDLE_DESCRIPTION, "湿度在可接受范围内，暂不处理");
        db.insert(TABLE_ALARM_RECORDS, null, mediumHumidityAlarmIgnored);
        
        // 创建气体报警记录
        
        // 高级别氧气报警
        ContentValues highOxygenAlarm = new ContentValues();
        highOxygenAlarm.put(COLUMN_ALARM_TYPE, "GAS");
        highOxygenAlarm.put(COLUMN_PARAM_TYPE, "oxygen");
        highOxygenAlarm.put(COLUMN_DEVICE_ID, 1);
        highOxygenAlarm.put(COLUMN_LOCATION, "仓库1-气体检测点1");
        highOxygenAlarm.put(COLUMN_VALUE, 17.8);
        highOxygenAlarm.put(COLUMN_UNIT, "%");
        highOxygenAlarm.put(COLUMN_THRESHOLD_MIN, 19);
        highOxygenAlarm.put(COLUMN_THRESHOLD_MAX, 23);
        highOxygenAlarm.put(COLUMN_LEVEL, "HIGH");
        highOxygenAlarm.put(COLUMN_STATUS, "ACTIVE");
        highOxygenAlarm.put(COLUMN_DESCRIPTION, "氧气浓度低于安全范围");
        highOxygenAlarm.put(COLUMN_CREATE_TIME, currentTime - 2 * 60 * 60 * 1000); // 2小时前
        highOxygenAlarm.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 2 * 60 * 60 * 1000)));
        db.insert(TABLE_ALARM_RECORDS, null, highOxygenAlarm);
        
        // 高级别二氧化碳报警
        ContentValues highCO2Alarm = new ContentValues();
        highCO2Alarm.put(COLUMN_ALARM_TYPE, "GAS");
        highCO2Alarm.put(COLUMN_PARAM_TYPE, "co2");
        highCO2Alarm.put(COLUMN_DEVICE_ID, 2);
        highCO2Alarm.put(COLUMN_LOCATION, "仓库2-气体检测点2");
        highCO2Alarm.put(COLUMN_VALUE, 0.62);
        highCO2Alarm.put(COLUMN_UNIT, "%");
        highCO2Alarm.put(COLUMN_THRESHOLD_MIN, 0);
        highCO2Alarm.put(COLUMN_THRESHOLD_MAX, 0.5);
        highCO2Alarm.put(COLUMN_LEVEL, "HIGH");
        highCO2Alarm.put(COLUMN_STATUS, "ACTIVE");
        highCO2Alarm.put(COLUMN_DESCRIPTION, "二氧化碳浓度高于安全范围");
        highCO2Alarm.put(COLUMN_CREATE_TIME, currentTime - 4 * 60 * 60 * 1000); // 4小时前
        highCO2Alarm.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 4 * 60 * 60 * 1000)));
        db.insert(TABLE_ALARM_RECORDS, null, highCO2Alarm);
        
        // 中级别磷化氢报警-已处理
        ContentValues mediumPH3AlarmHandled = new ContentValues();
        mediumPH3AlarmHandled.put(COLUMN_ALARM_TYPE, "GAS");
        mediumPH3AlarmHandled.put(COLUMN_PARAM_TYPE, "ph3");
        mediumPH3AlarmHandled.put(COLUMN_DEVICE_ID, 3);
        mediumPH3AlarmHandled.put(COLUMN_LOCATION, "仓库3-气体检测点1");
        mediumPH3AlarmHandled.put(COLUMN_VALUE, 0.008);
        mediumPH3AlarmHandled.put(COLUMN_UNIT, "mg/m³");
        mediumPH3AlarmHandled.put(COLUMN_THRESHOLD_MIN, 0);
        mediumPH3AlarmHandled.put(COLUMN_THRESHOLD_MAX, 0.01);
        mediumPH3AlarmHandled.put(COLUMN_LEVEL, "MEDIUM");
        mediumPH3AlarmHandled.put(COLUMN_STATUS, "HANDLED");
        mediumPH3AlarmHandled.put(COLUMN_DESCRIPTION, "磷化氢浓度接近安全上限");
        mediumPH3AlarmHandled.put(COLUMN_CREATE_TIME, currentTime - 36 * 60 * 60 * 1000); // 36小时前
        mediumPH3AlarmHandled.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 36 * 60 * 60 * 1000)));
        mediumPH3AlarmHandled.put(COLUMN_HANDLE_TIME, currentTime - 34 * 60 * 60 * 1000); // 34小时前处理
        mediumPH3AlarmHandled.put(COLUMN_HANDLE_USER, "admin");
        mediumPH3AlarmHandled.put(COLUMN_HANDLE_DESCRIPTION, "已启动通风系统");
        db.insert(TABLE_ALARM_RECORDS, null, mediumPH3AlarmHandled);
        
        // 低级别氧气报警-已忽略
        ContentValues lowOxygenAlarmIgnored = new ContentValues();
        lowOxygenAlarmIgnored.put(COLUMN_ALARM_TYPE, "GAS");
        lowOxygenAlarmIgnored.put(COLUMN_PARAM_TYPE, "oxygen");
        lowOxygenAlarmIgnored.put(COLUMN_DEVICE_ID, 1);
        lowOxygenAlarmIgnored.put(COLUMN_LOCATION, "仓库1-气体检测点2");
        lowOxygenAlarmIgnored.put(COLUMN_VALUE, 18.9);
        lowOxygenAlarmIgnored.put(COLUMN_UNIT, "%");
        lowOxygenAlarmIgnored.put(COLUMN_THRESHOLD_MIN, 19);
        lowOxygenAlarmIgnored.put(COLUMN_THRESHOLD_MAX, 23);
        lowOxygenAlarmIgnored.put(COLUMN_LEVEL, "LOW");
        lowOxygenAlarmIgnored.put(COLUMN_STATUS, "IGNORED");
        lowOxygenAlarmIgnored.put(COLUMN_DESCRIPTION, "氧气浓度略低于安全范围");
        lowOxygenAlarmIgnored.put(COLUMN_CREATE_TIME, currentTime - 48 * 60 * 60 * 1000); // 48小时前
        lowOxygenAlarmIgnored.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(currentTime - 48 * 60 * 60 * 1000)));
        lowOxygenAlarmIgnored.put(COLUMN_HANDLE_TIME, currentTime - 47 * 60 * 60 * 1000); // 47小时前处理
        lowOxygenAlarmIgnored.put(COLUMN_HANDLE_USER, "operator");
        lowOxygenAlarmIgnored.put(COLUMN_HANDLE_DESCRIPTION, "氧气浓度接近正常范围，暂不处理");
        db.insert(TABLE_ALARM_RECORDS, null, lowOxygenAlarmIgnored);
        
        // 添加一些历史报警记录（1-7天前）
        for (int i = 1; i <= 20; i++) {
            // 随机选择报警类型
            String alarmType = Math.random() > 0.5 ? "GRAIN" : "GAS";
            
            // 随机选择参数类型
            String paramType;
            if (alarmType.equals("GRAIN")) {
                paramType = Math.random() > 0.5 ? "temperature" : "humidity";
            } else {
                double rand = Math.random();
                if (rand < 0.33) {
                    paramType = "oxygen";
                } else if (rand < 0.66) {
                    paramType = "co2";
                } else {
                    paramType = "ph3";
                }
            }
            
            // 随机选择设备ID
            int deviceId = (int) (Math.random() * 3) + 1;
            
            // 随机选择位置
            String location;
            if (alarmType.equals("GRAIN")) {
                location = "仓库" + deviceId + "-测点" + ((int) (Math.random() * 5) + 1);
            } else {
                location = "仓库" + deviceId + "-气体检测点" + ((int) (Math.random() * 3) + 1);
            }
            
            // 随机选择值、单位和阈值
            double value;
            String unit;
            double thresholdMin;
            double thresholdMax;
            
            switch (paramType) {
                case "temperature":
                    value = Math.random() * 40;
                    unit = "℃";
                    thresholdMin = 5;
                    thresholdMax = 35;
                    break;
                case "humidity":
                    value = Math.random() * 100;
                    unit = "%";
                    thresholdMin = 45;
                    thresholdMax = 75;
                    break;
                case "oxygen":
                    value = Math.random() * 5 + 17;
                    unit = "%";
                    thresholdMin = 19;
                    thresholdMax = 23;
                    break;
                case "co2":
                    value = Math.random() * 0.8;
                    unit = "%";
                    thresholdMin = 0;
                    thresholdMax = 0.5;
                    break;
                default: // ph3
                    value = Math.random() * 0.02;
                    unit = "mg/m³";
                    thresholdMin = 0;
                    thresholdMax = 0.01;
                    break;
            }
            
            // 根据值和阈值确定报警级别
            String level;
            if (paramType.equals("temperature") || paramType.equals("humidity")) {
                if (value < thresholdMin * 0.9 || value > thresholdMax * 1.1) {
                    level = "HIGH";
                } else if (value < thresholdMin * 0.95 || value > thresholdMax * 1.05) {
                    level = "MEDIUM";
                } else {
                    level = "LOW";
                }
            } else {
                if (paramType.equals("oxygen") && value < thresholdMin * 0.9) {
                    level = "HIGH";
                } else if ((paramType.equals("co2") || paramType.equals("ph3")) && value > thresholdMax * 1.1) {
                    level = "HIGH";
                } else if (paramType.equals("oxygen") && value < thresholdMin * 0.95) {
                    level = "MEDIUM";
                } else if ((paramType.equals("co2") || paramType.equals("ph3")) && value > thresholdMax * 1.05) {
                    level = "MEDIUM";
                } else {
                    level = "LOW";
                }
            }
            
            // 随机选择状态
            String status;
            double statusRand = Math.random();
            if (statusRand < 0.4) {
                status = "ACTIVE";
            } else if (statusRand < 0.7) {
                status = "HANDLED";
            } else {
                status = "IGNORED";
            }
            
            // 创建报警记录
            ContentValues historyAlarm = new ContentValues();
            historyAlarm.put(COLUMN_ALARM_TYPE, alarmType);
            historyAlarm.put(COLUMN_PARAM_TYPE, paramType);
            historyAlarm.put(COLUMN_DEVICE_ID, deviceId);
            historyAlarm.put(COLUMN_LOCATION, location);
            historyAlarm.put(COLUMN_VALUE, value);
            historyAlarm.put(COLUMN_UNIT, unit);
            historyAlarm.put(COLUMN_THRESHOLD_MIN, thresholdMin);
            historyAlarm.put(COLUMN_THRESHOLD_MAX, thresholdMax);
            historyAlarm.put(COLUMN_LEVEL, level);
            historyAlarm.put(COLUMN_STATUS, status);
            
            // 设置描述
            String description;
            if (paramType.equals("temperature")) {
                description = value < thresholdMin ? "温度低于安全范围" : "温度高于安全范围";
            } else if (paramType.equals("humidity")) {
                description = value < thresholdMin ? "湿度低于安全范围" : "湿度高于安全范围";
            } else if (paramType.equals("oxygen")) {
                description = "氧气浓度" + (value < thresholdMin ? "低于" : "高于") + "安全范围";
            } else if (paramType.equals("co2")) {
                description = "二氧化碳浓度高于安全范围";
            } else { // ph3
                description = "磷化氢浓度高于安全范围";
            }
            historyAlarm.put(COLUMN_DESCRIPTION, description);
            
            // 设置创建时间（1-7天内随机）
            long createTime = currentTime - (24 * 60 * 60 * 1000L) * (1 + (int) (Math.random() * 6));
            historyAlarm.put(COLUMN_CREATE_TIME, createTime);
            historyAlarm.put(COLUMN_CREATE_TIME_STRING, sdf.format(new Date(createTime)));
            
            // 如果状态不是ACTIVE，设置处理时间和处理人
            if (!status.equals("ACTIVE")) {
                long handleTime = createTime + (int) (Math.random() * 3 * 60 * 60 * 1000); // 0-3小时后处理
                historyAlarm.put(COLUMN_HANDLE_TIME, handleTime);
                historyAlarm.put(COLUMN_HANDLE_USER, Math.random() > 0.5 ? "admin" : "operator");
                historyAlarm.put(COLUMN_HANDLE_DESCRIPTION, status.equals("HANDLED") ? 
                        "已" + (alarmType.equals("GRAIN") ? "调整环境参数" : "处理气体浓度") : 
                        "暂不处理，继续观察");
            }
            
            db.insert(TABLE_ALARM_RECORDS, null, historyAlarm);
        }
        
        Log.i(TAG, "默认报警记录创建完成");
    }
} 